package com.jabo.douban.demo.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 朋友圈9宫格图片View
 * 1. 一张图片的时候，需要设置maxHeight和maxWidth
 * 2. 4张图片的时候，需要设置两行显示每行两张
 * 3. 9张图片的时候，需要设置三行显示每行三张（最多9张照片）
 * 4. 其余张数图片，就根据图片的个数显示每行显示三个
 *
 * @anthor JZheng3
 * @Time: 2020/3/4
 */
public class NinePictureLayout extends ViewGroup {

    private int mPerLineViewNum = 3;//每行显示三个
    private int mRawSpace = 20;//每个view之间的列距
    private int mLineSpace = 20;//行距
    private int mPerLineRawSpaceNum = 2; //每行列距的个数
    private int mChildWidthSize;
    private int mChildHeightSize;
    private int mAllLines; //当前有几行子View

    private int mOnlyOneChildMaxHeight = 800;
    private int mOnlyOneChildMaxWidth = 600;

    private int mDefaultChildWidth = 200;

    public NinePictureLayout(@NonNull Context context) {
        this(context, null);
    }

    public NinePictureLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NinePictureLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setWillNotDraw(false);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //根据父View的宽，来设置每个子View的宽度
        int viewSelfWidth = MeasureSpec.getSize(widthMeasureSpec);
        int viewSelfHeight = MeasureSpec.getSize(heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int childWidthMeasureSpec;
        int childHeightMeasureSpec;

        int childCount = getChildCount();
        mAllLines = (int) Math.ceil((float) childCount / mPerLineViewNum);

        //如果只有一张图，那么就根据子View自己的尺寸来
        if (childCount == 1) {
            //对于加载这种不固定
            View childAt = getChildAt(0);
            measureChild(childAt, widthMeasureSpec, heightMeasureSpec);

            if (widthMode != MeasureSpec.EXACTLY) {
                viewSelfWidth = childAt.getMeasuredWidth();
            }

            if (heightMode != MeasureSpec.EXACTLY) {
                viewSelfHeight = childAt.getMeasuredHeight();
            }

            Log.e("zjb", "onMeasure: viewSelfHeight:" + viewSelfHeight + ";viewSelfWidth:" + viewSelfWidth);
            setMeasuredDimension(viewSelfWidth, viewSelfHeight);
//            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;

        }

        //如果当前ViewGroup宽度是确定的，根据当前的宽度去确定子View的宽度
        if (widthMode == MeasureSpec.EXACTLY) {
            int childWidthMode = MeasureSpec.EXACTLY;
            //每行总ChildView的宽度
            int lineAllChildViewsWidth = viewSelfWidth - getPaddingLeft() - getPaddingRight() - mPerLineRawSpaceNum * mRawSpace;
            mChildWidthSize = lineAllChildViewsWidth / mPerLineViewNum;
            childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mChildWidthSize, childWidthMode);
        } else {
            //如果当前ViewGroup不确定，根据子View的宽度确定父View的宽度
            int childWidthMode = MeasureSpec.EXACTLY;
            mChildWidthSize = mDefaultChildWidth;
            childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mDefaultChildWidth, childWidthMode);
            //当前View的真正宽度
            viewSelfWidth = mDefaultChildWidth * mPerLineViewNum + mPerLineRawSpaceNum * mPerLineViewNum + getPaddingLeft() + getPaddingRight();
        }

        if (heightMode != MeasureSpec.EXACTLY) {
            viewSelfHeight = mAllLines * mChildWidthSize + (mAllLines - 1) * mLineSpace;
        }

        //因为子View是正方形的，所以宽高一样
        mChildHeightSize = mChildWidthSize;
        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mChildHeightSize, MeasureSpec.EXACTLY);
        for (int i = 0; i < childCount; i++) {
            View view = getChildAt(i);
            view.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }

        setMeasuredDimension(viewSelfWidth, viewSelfHeight);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        int lineWidth = getPaddingLeft();
        int lineHeight = getPaddingTop();

        if (mUrls.isEmpty()) {
            setVisibility(GONE);
            return;
        }
        int childCount = getChildCount();

        Log.e("zjb", "onLayout: start,dataSize：");

        for (int i = 0; i < childCount; i++) {

            ImageView child = (ImageView) getChildAt(i);
            String url = mUrls.get(i);
            if (mLoadImageUrl != null) {
                mLoadImageUrl.loadImageUrl(getContext(), url, child);
            }

            if (childCount == 4) {//四张图需要显示两行
                if (i == 2) {
                    lineHeight += child.getMeasuredHeight() + mLineSpace;
                    lineWidth = getPaddingLeft();
                }
            } else {
                if (i % mPerLineViewNum == 0 && i != 0) {
                    lineHeight += child.getMeasuredHeight() + mLineSpace;
                    lineWidth = getPaddingLeft();
                }
            }

            child.layout(lineWidth, lineHeight, lineWidth + child.getMeasuredWidth(), lineHeight + child.getMeasuredHeight());
            lineWidth += child.getMeasuredWidth() + mRawSpace;
        }
    }


    private List<String> mUrls = new ArrayList<>();
    private LoadImageUrl mLoadImageUrl;

    public void setUrls(List<String> urls, int position) {
        removeAllViews();
        mUrls.clear();
        mUrls.addAll(urls);
        int dataSize = mUrls.size();
        for (int i = 0; i < dataSize; i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            addView(imageView);
        }
        Log.e("zjb", "setUrls: start,dataSize：" + dataSize);
    }

    public void setLoadImageUrl(LoadImageUrl loadImageUrl) {
        mLoadImageUrl = loadImageUrl;
    }

    public interface LoadImageUrl {
        void loadImageUrl(Context context, String url, ImageView imageView);
    }
}
